<?php

Yii::import('application.social_login.*');
require 'facebook/facebook.php';
require 'config_social/fbconfig.php';
require_once 'google/Google_Client.php';
require_once 'google/contrib/Google_PlusService.php';
require_once 'google/contrib/Google_Oauth2Service.php';

class UserController extends Controller {

    const PAGE_SIZE = 10;

    private $_model;

    public function filters() {
        return array(
            'accessControl',
        );
    }

    public function accessRules() {
        return array(
            array('allow', // allow all users
                'actions' => array(/* 'index', */ 'view', 'registration', 'captcha', 'login', 'recovery', 'activation', 'loginpop', 'registrationpop', 'activationpop', 'loginpopforcheckout', 'registrationpopcheckout', 'recoverypop', 'forgotpasswordpop'),
                'users' => array('*'),
            /* 'expression' => "SkillConfig::isPostOwner('Member')", */
            ),
            array('allow', // allow authenticated user
                'actions' => array('createprofile', 'myprofile', 'edit', 'logout', 'changepassword'),
                'users' => array('@'),
            ),
            array('allow', // allow admin user
                'actions' => array(/* 'admin', */ 'delete', 'edit', 'changepassword'/* ,'create', 'update', 'list', 'assign', 'changestatus' */, 'myprofile'),
                'users' => User::getAdmins(),
            ),
            array('deny', // deny all other users
                'users' => array('*'),
            ),
        );
    }

    public function actions() {
        return array(
            'captcha' => array(
                'class' => 'CCaptchaAction',
                'backColor' => 0xFFFFFF,
            ),
        );
    }

    public function actionIndex() {
        if (Yii::app()->user->isGuest) {
            $this->actionLogin();
        } else if (isset($_GET['id']) || isset($_GET['user_id'])) {
            $this->actionProfile();
        } else {
            $this->actionList();
        }
    }

    public function actionRegistration() {
        $this->layout = 'frontend.www.themes.front-end.views.layouts.detailspage';
        $form = new RegistrationForm;
// User is already logged in?
        if (isset($_POST['RegistrationForm'])) {
            $form->attributes = $_POST['RegistrationForm'];
            if ($form->validate()) {
                $user = User::model()->findByAttributes(array('username' => $form->username, 'status' => 0));
                if (!empty($user)) {
                    $user->register($form->username, $form->password, $form->email, $form->issubscribe, '');
                } else {
                    $user = new User();
                    $user->register($form->username, $form->password, $form->email, $form->issubscribe, '');
                }
                $userRole = new UserHasRole();
                (Yii::app()->user->getState('trainer') != 2) ? $userRole->setAttribute('role_id', SkillConfig::USER_TRAINER) : $userRole->setAttribute('role_id', SkillConfig::WEB_USER);
                $userRole->setAttribute('user_id', $user->id);
                $userRole->save(false);
                $profile = new Profile();
                $profile->user_id = $user->id;
                $profile->save();
                Yii::app()->user->setState('trainer', NULL);
                if (Yii::app()->controller->module->disableEmailActivation == true) {
                    Yii::app()->user->setFlash('registration', Yii::t("UserModule.user", "Your Account has been activated. Thank you for your registration."));
                    $this->refresh();
                } else {
                    $this->sendRegistrationEmail($user);
                }
                if (UserModule::$allowInactiveAcctLogin) {
                    if (Yii::app()->user->allowAutoLogin) {
                        $identity = new UserIdentity($model->username, $sourcePassword);
                        $identity->authenticate();
                        Yii::app()->user->login($identity, 0);
                        $this->redirect($this->module->returnUrl);
                    } else {
                        Yii::app()->user->setFlash('registration', Yii::t("UserModule.user", "Thank you for your registration. Please check your email or login."));
                        $this->refresh();
                    }
                } else {
                    Yii::app()->user->setFlash('registration', Yii::t("UserModule.user", "Thank you for your registration. Please check your email."));
                    $this->refresh();
                }
            }
        }

        $this->render('/user/registration', array('form' => $form));
    }

    /* PopUp Login and register */

    public function actionLoginpop() {
        $this->layout = 'mainpop';
        // collect user input data
        if (isset($_POST['UserLogin'])) {
            $model = new UserLogin();
            $model->attributes = $_POST['UserLogin'];
            // validate user input and redirect to previous page if valid
            if ($model->validate()) {
                $lastVisit = User::model()->findByPk(Yii::app()->user->id);
                $lastVisit->setAttribute('lastvisit', time());
                $lastVisit->save();
                $profile = Profile::model()->findByAttributes(array('user_id' => Yii::app()->user->id));
                $uname = $profile->first_name . ' ' . $profile->last_name;
                $_SESSION['id'] = Yii::app()->user->id;
                ShoppingCartByUser::saveCartbyUser(Yii::app()->user->id);
                ShoppingCartByUser::putShoppingCart();
                echo CJSON::encode(array(
                    'status' => 'success',
                    'uid' => Yii::app()->user->id,
                    'email' => $lastVisit->username,
                    'name' => $uname,
                ));
                Yii::app()->end();
            } else {
                $error = CActiveForm::validate($model);
                if ($error != '[]')
                    echo $error;
                Yii::app()->end();
            }
        }
        // display the login form
        $this->render('/user/loginpop');
    }

    public function actionLoginpopforcheckout() {
        $this->layout = 'mainpop';
        $securituhashEBS = '';
        // collect user input data
        if (isset($_POST['UserLogin'])) {
            $model = new UserLogin();
            $model->attributes = $_POST['UserLogin'];
            // validate user input and redirect to previous page if valid
            if ($model->validate()) {
                $lastVisit = User::model()->findByPk(Yii::app()->user->id);
                $lastVisit->setAttribute('lastvisit', time());
                $lastVisit->save();
                $profile = Profile::model()->findByAttributes(array('user_id' => Yii::app()->user->id));
                $uname = $profile->first_name . ' ' . $profile->last_name;
                $phon_no = $profile->phone;

                $_SESSION['id'] = Yii::app()->user->id;

                if (Yii::app()->user->id) {
                    $securituhashEBS = ShoppingCartByUser::EBS_secure_hash(Yii::app()->session['totalamountcart']);
                    ShoppingCartByUser::saveCartbyUser(Yii::app()->user->id);
                }
                echo CJSON::encode(array(
                    'status' => 'success',
                    'uid' => Yii::app()->user->id,
                    'email' => $lastVisit->username,
                    'name' => $uname,
                    'phon_no' => $phon_no,
                    'securityhashEBS' => $securituhashEBS,
                    'amount' => Yii::app()->session['totalamountcart'],
                ));
                Yii::app()->end();
            } else {
                $error = CActiveForm::validate($model);
                if ($error != '[]')
                    echo $error;
                Yii::app()->end();
            }
        }
        // display the login form
        $this->render('/user/loginpopforcheckout');
    }

    public function actionRegistrationpopcheckout() {
        $securituhashEBS = '';
        if (isset($_POST['RegistrationForm'])) {
            $form = new RegistrationForm;
            $modellogin = new UserLogin();
            $form->attributes = $_POST['RegistrationForm'];
            if ($form->validate()) {
                $user = new User();
                if ($user->register($form->username, $form->password, $form->email, $form->issubscribe, 'checkout')) {
                    $profile = new Profile();
                    $profile->user_id = $user->id;
                    $profile->save();
                    self::sendRegistrationEmailPop($user);
                    $identity = new UserIdentity($form->username, $form->password);
                    $identity->authenticate();
                    Yii::app()->user->login($identity);
                    $_SESSION['id'] = Yii::app()->user->id;

                    if (Yii::app()->user->id) {
                        $securituhashEBS = ShoppingCartByUser::EBS_secure_hash(Yii::app()->session['totalamountcart']);
                        ShoppingCartByUser::saveCartbyUser(Yii::app()->user->id);
                    }
                }
                echo CJSON::encode(array(
                    'status' => 'success',
                    'uid' => Yii::app()->user->id,
                    'email' => $form->username,
                    'name' => '',
                    'phon_no' => '',
                    'securityhashEBS' => $securituhashEBS,
                    'amount' => Yii::app()->session['totalamountcart'],
                ));
                Yii::app()->end();
            } else {
                $error = CActiveForm::validate($form);
                if ($error != '[]')
                    echo $error;
                Yii::app()->end();
            }
        }
    }

    public function actionRegistrationpop() {
        if (isset($_POST['RegistrationForm'])) {
            $form = new RegistrationForm;
            $form->attributes = $_POST['RegistrationForm'];
            if ($form->validate()) {
                $user = new User();
                if ($user->register($form->username, $form->password, $form->email, $form->issubscribe, '')) {
                    $profile = new Profile();
                    $profile->user_id = $user->id;
                    $profile->save();
                    self::sendRegistrationEmailPop($user);
                    //Yii::app()->user->setFlash('registration', Yii::t("UserModule.user", "Thank you for your registration. Please check your email."));
                }

                echo CJSON::encode(array(
                    'status' => 'success',
                    'email' => $user->username,
                ));
                Yii::app()->end();
            } else {
                $error = CActiveForm::validate($form);
                if ($error != '[]')
                    echo $error;
                Yii::app()->end();
            }
        }
    }

    function sendRegistrationEmailPop($user) {
        $mailmodel = EmailTemplate::model()->findByPk(Message::REGISTRATION_TEMPLATE_POP);
        $activation_url = 'http://' . $_SERVER['HTTP_HOST'] . $this->createUrl('user/activation', array("activationKey" => $user->activationKey, "skillusers" => $user->username));
        $mailbody = array('value' => $mailmodel->body, 'type' => 'raw');
        $subject = $mailmodel->subject;
        $mailto = $user->username;
        $arrayFind = array('[username]', '[activationkey]');
        $arrayReplace = array($mailto, $user->activationKey);
        $mailbody = str_replace($arrayFind, $arrayReplace, $mailbody);
        $mailtemp = Template::model()->findByPk($mailmodel->template_id);
        $subject = $mailmodel->subject;
        $body = $this->renderPartial('frontend.www.themes.front-end.views.mails/' . $mailtemp->filename, array('mailbody' => $mailbody['value']), true, false);
        try {
            SkillSendMail::SendMail($mailto, $subject, $body);
            /* $this->redirect(array('view', 'id' => $model->id)); */
        } catch (Exception $e) {
            echo $e;
            exit;
        }
        return true;
    }

    public function actionActivationpop() {

        $user = new User();
        $returnval = '';
        $find = $user->findByAttributes(array('username' => trim($_POST['email'])));
        if ($find->status == 1) {
            $returnval = "activated";
        } elseif ($find->activationKey == $_POST['activationKey']) {
            $find->activationKey = User::encrypt(microtime());
            $find->status = 1;
            if ($find->save()) {
                $returnval = "activated";
            } else {
                $returnval = "not activated";
            }
        }
        echo CJSON::encode(array(
            'status' => $returnval,
        ));
        Yii::app()->end();
    }

    /* PopUp Login and register */

    public function sendRegistrationEmail($user) {
        $mailmodel = EmailTemplate::model()->findByPk(Message::REGISTRATION_TEMPLATE);
        $activation_url = 'http://' . $_SERVER['HTTP_HOST'] . $this->createUrl('user/activation', array("activationKey" => $user->activationKey, "skillusers" => $user->username));
        $mailbody = array('value' => $mailmodel->body, 'type' => 'raw');
        $subject = $mailmodel->subject;
        $mailto = $user->username;
        $arrayFind = array('[username]', '[activation_link]');
        $arrayReplace = array($mailto, $activation_url);
        $mailbody = str_replace($arrayFind, $arrayReplace, $mailbody);
        $mailtemp = Template::model()->findByPk($mailmodel->template_id);
        $subject = $mailmodel->subject;
        $body = $this->renderPartial('frontend.www.themes.front-end.views.mails/' . $mailtemp->filename, array('mailbody' => $mailbody['value']), true, false);
        try {
            SkillSendMail::SendMail($mailto, $subject, $body);
            /* $this->redirect(array('view', 'id' => $model->id)); */
        } catch (Exception $e) {
            echo $e;
            exit;
        }
        return true;
    }

    public function actionLogin() {
        $profile = new Profile;
        $userModel = new User();
        $this->layout = 'frontend.www.themes.front-end.views.layouts.detailspage';
        /* Facebook Login */
        if (isset($_GET['oauth_provider'])) {
            $oauth_provider = $_GET['oauth_provider'];
            if ($oauth_provider == 'facebook') {
                $facebook = new Facebook(array(
                            'appId' => '1433437273566460',
                            'secret' => '836315ea0d8c4a88df00fb8a102779bd',
                        ));
                $user = $facebook->getUser();
                if ($user) {
                    $user_profile = $facebook->api('/me');
                    $haModel = HaLogins::model()->findByAttributes(array('login_provider_identifier' => $user_profile['email']));
                    if (!$haModel) {
                        HaLogins::saveUser($user_profile['id'], $user_profile['email'], $oauth_provider);
                        $checkdata = $userModel->findByAttributes(array('username' => $user_profile['email']));
                        if (empty($checkdata)) {
                            if ($userModel->register($user_profile['email'], $user_profile['email'], $user_profile['email'], 0, 'checkout')) {
                                $profile = new Profile();
                                $profile->user_id = $userModel->id;
                                $profile->save();
                                $this->auto_login($user_profile['email']);
                            }
                        } else {
                            if ($checkdata->status != SkillConfig::STATUS_ACTIVE) {
                                $userModel->updateByPk($checkdata->id, array('status' => SkillConfig::STATUS_ACTIVE));
                            }
                            $checkdataprofile = $profile->findByAttributes(array('user_id' => $checkdata->id));
                            if (!$checkdataprofile) {
                                $profile->user_id = $checkdata->id;
                                $profile->save();
                                $this->auto_login($user_profile['email']);
                            } else {
                                $this->auto_login($user_profile['email']);
                            }
                        }
                    } else {
                        $this->auto_login($user_profile['email']);
                    }
                } else {

                    $login_url = $facebook->getLoginUrl(array('scope' => 'email'));
                    header("Location: " . $login_url);
                }
            }
        }

        $client = new Google_Client();
        $client->setApplicationName("skillhippologin");
        $client->setScopes(array('https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/plus.me'));
        $client->setClientId('1082743347334-4m9ik2t4kv8fuj5fg3pfpun4eve4c0cj.apps.googleusercontent.com');
        $client->setClientSecret('A7bNtCLnEGZ_mWFYA5h6K5CS');
        $client->setRedirectUri(SITE_URL . 'user/user/login/');
        $client->setDeveloperKey('1082743347334-4m9ik2t4kv8fuj5fg3pfpun4eve4c0cj.apps.googleusercontent.com');
        $plus = new Google_PlusService($client);
        $oauth2 = new Google_Oauth2Service($client);
        $authUrlGoogle = $client->createAuthUrl();


        if (isset($_GET['code']) && !isset($_GET['oauth_provider'])) {
            $client->authenticate();
            $_SESSION['access_token'] = $client->getAccessToken();
            if ($client->getAccessToken()) {
                $guser = $oauth2->userinfo->get();
                $me = $plus->people->get('me');
                $haModel = HaLogins::model()->findByAttributes(array('login_provider_identifier' => $guser['email']));
                if (!$haModel) {
                    HaLogins::saveUser($me['id'], $guser['email'], 'google');
                    $userModel = new User();
                    if ($userModel->register($guser['email'], $guser['email'], $guser['email'], 0, 'checkout')) {
                        $profile = new Profile();
                        $profile->user_id = $userModel->id;
                        $profile->save();
                        $this->auto_login($guser['email']);
                    }
                    HaLogins::saveUser($me['id'], $guser['email'], 'google');
                    $checkdata = $userModel->findByAttributes(array('username' => $guser['email']));
                    if (!$checkdata) {
                        if ($userModel->register($guser['email'], $guser['email'], $guser['email'], 0, 'checkout')) {
                            $profile = new Profile();
                            $profile->user_id = $userModel->id;
                            $profile->save();
                            $this->auto_login($guser['email']);
                        }
                    } else {
                        if ($checkdata->status != SkillConfig::STATUS_ACTIVE) {
                            $userModel->updateByPk($checkdata->id, array('status' => SkillConfig::STATUS_ACTIVE));
                        }
                        $checkdataprofile = $profile->findByAttributes(array('user_id' => $checkdata->id));
                        if (!$checkdataprofile) {
                            $profile->user_id = $checkdata->id;
                            $profile->save();
                            $this->auto_login($guser['email']);
                        } else {
                            $this->auto_login($guser['email']);
                        }
                    }
                } else {
                    $this->auto_login($guser['email']);
                }
            }
        }



        $model = new UserLogin;
        if (isset($_POST['UserLogin'])) {
            $model->attributes = $_POST['UserLogin'];
            // validate user input and redirect to previous page if valid
            if ($model->validate()) {
                $lastVisit = User::model()->findByPk(Yii::app()->user->id);
                $lastVisit->setAttribute('lastvisit', time());
                $lastVisit->save();
                $_SESSION['id'] = Yii::app()->user->id;
                //  ShoppingCartByUser::saveCartbyUser(Yii::app()->user->id);
                //ShoppingCartByUser::putShoppingCart();
                $this->redirect(Yii::app()->user->returnUrl);
            }
        }
        // display the login form
        $this->render('/user/login', array('model' => $model, 'authUrlGoogle' => $authUrlGoogle));
    }

    public function actionLogout() {
        Yii::app()->user->logout();
        $this->redirect($this->module->returnLogoutUrl);
    }

    /**
     * Activation of an user account
     */
    public function actionActivation() {
        $this->layout = 'frontend.www.themes.front-end.views.layouts.detailspage';
        $user = new User();

        if ($user->activate($_GET['skillusers'], $_GET['activationKey'])) {
            $this->senduserActivationEmail($_GET['skillusers']);
            $udata = $user->findByAttributes(array('username' => $_GET['skillusers']));
            $loginpassword = $udata->password;
            $udata->password = User::encrypt($loginpassword);
            $udata->save();

            $identity = new UserIdentity($_GET['skillusers'], $loginpassword);
            $identity->authenticate();
            Yii::app()->user->login($identity);
            $_SESSION['id'] = Yii::app()->user->id;
            $this->redirect(Yii::app()->homeUrl);
        } else {
            $this->render('/user/message', array(
                'title' => Yii::t("UserModule.user", "User activation"),
                'content' => Yii::t("UserModule.user", "Incorrect activation URL.")));
        }
    }

    /**
     * Change password
     */
    public function actionChangepassword() {
        $form = new UserChangePassword;
        if (isset(Yii::app()->user->id)) {
            if (isset($_POST['UserChangePassword'])) {
                $form->attributes = $_POST['UserChangePassword'];
                if ($form->validate()) {
                    $new_password = User::model()->findByPk(Yii::app()->user->id);
                    $new_password->password = User::encrypt($form->password);
                    $new_password->activationKey = User::encrypt(microtime() . $form->password);

                    if ($new_password->save(false)) {

                        Yii::app()->user->setFlash('profileMessage', Yii::t("UserModule.user", "Your new password has been saved."));
                        $this->redirect(array("user/myprofile"));
                    } else {
                        Yii::app()->user->setFlash('profileMessage', Yii::t("UserModule.user", "There was an error saving your password."));
                        $this->redirect(array("user/myprofile"));
                    }
                }
            }
            $this->render('/user/changepassword', array('form' => $form));
        } else {
            // No id was set. An error has occured. (should never get here)
            $this->redirect($this->module->returnUrl);
        }
    }

    public function actionForgotpasswordpop() {
        $securituhashEBS = '';
        $amoutincart = '';
        if (isset($_POST['activation_key']) && $_POST['activation_key'] <> "") {
            $new_password = User::model()->findByAttributes(array('activationKey' => $_POST['activation_key']));
            if ($new_password != "") {
                $new_password->password = md5($_POST['password']);
                $new_password->status = SkillConfig::STATUS_ACTIVE;
                if ($new_password->save(false)) {
                    $identity = new UserIdentity($new_password->username, $_POST['password']);
                    $identity->authenticate();
                    Yii::app()->user->login($identity);

                    if (isset(Yii::app()->user->id)) {
                        $profile = Profile::model()->findByAttributes(array('user_id' => Yii::app()->user->id));
                        $uname = $profile->first_name . ' ' . $profile->last_name;
                        $phon_no = $profile->phone;
                        $_SESSION['id'] = Yii::app()->user->id;
                        if (Yii::app()->user->id) {
                            if (Yii::app()->session['totalamountcart'] <> "") {
                                $securituhashEBS = ShoppingCartByUser::EBS_secure_hash(Yii::app()->session['totalamountcart']);
                                $amoutincart = Yii::app()->session['totalamountcart'];
                            }
                            ShoppingCartByUser::saveCartbyUser(Yii::app()->user->id);
                        }
                        ShoppingCartByUser::putShoppingCart();
                        echo CJSON::encode(array(
                            'status' => 'success',
                            'uid' => Yii::app()->user->id,
                            'name' => $uname,
                            'email' => $new_password->username,
                            'phon_no' => $phon_no,
                            'securityhashEBS' => $securituhashEBS,
                            'amount' => $amoutincart,
                        ));
                        Yii::app()->end();
                    } else {
                        echo CJSON::encode(array(
                            'status' => 'fail',
                        ));
                        Yii::app()->end();
                    }
                } else {
                    echo CJSON::encode(array(
                        'status' => 'fail',
                    ));
                    Yii::app()->end();
                }
            } else {
                echo CJSON::encode(array(
                    'status' => 'fail',
                ));
                Yii::app()->end();
            }
        }
    }

    /**
     * Recover password
     */
    public function actionRecovery() {
        $this->layout = 'frontend.www.themes.front-end.views.layouts.detailspage';
        $form = new UserRecoveryForm;
        // User is already logged in
        if (($uid = Yii::app()->user->id) === true) {
            $this->redirect($this->module->returnUrl);
        } else {
            if (isset($_GET['username']) && isset($_GET['activationKey'])) {
                $email = $_GET['username'];
                $activationKey = $_GET['activationKey'];
                $form2 = new UserChangePassword;
                $find = User::model()->findByAttributes(array('username' => $email));
                if ($find->activationKey == $activationKey) {
                    if (isset($_POST['UserChangePassword'])) {
                        $form2->attributes = $_POST['UserChangePassword'];
                        if ($form2->validate()) {
                            $find->password = User::encrypt($form2->password);
                            $find->activationKey = User::encrypt(microtime() . $form2->password);
                            $find->save();
                            $identity = new UserIdentity($email, $form2->password);
                            $identity->authenticate();
                            Yii::app()->user->login($identity);
                            $_SESSION['id'] = Yii::app()->user->id;
                            $this->redirect(Yii::app()->homeUrl);
                        }
                    }
                    $this->render('/user/changepassword', array('form' => $form2));
                } else {
                    Yii::app()->user->setFlash('recoveryMessage', Yii::t("user", "Incorrect recovery link."));
                    $this->redirect('http://' . $_SERVER['HTTP_HOST'] . $this->createUrl('user/recovery'));
                }
            } else {
                if (isset($_POST['UserRecoveryForm'])) {
                    $form->attributes = $_POST['UserRecoveryForm'];
                    if ($form->validate()) {
                        $user = User::model()->findbyPk($form->user_id);
                        $user->setAttribute('activationKey', guid());
                        $user->save();
                        $activation_url = 'http://' . $_SERVER['HTTP_HOST'] . $this->createUrl('user/recovery', array("activationKey" => $user->activationKey, "username" => $user->username));
                        $this->forgatePasswordEmail($user->username, $activation_url);
                        Yii::app()->user->setFlash('recoveryMessage', Yii::t("user", "Instructions have been sent to you. Please check your EMail."));
                        $this->refresh();
                    }
                }
                $this->render('/user/recovery', array('form' => $form));
            }
        }
    }

    public function actionRecoverypop() {
        $form = new UserRecoveryForm;
        if (isset($_POST['UserRecoveryForm'])) {
            $form->attributes = $_POST['UserRecoveryForm'];
            if ($form->validate()) {
                $user = User::model()->findbyPk($form->user_id);
                $user->setAttribute('activationKey', guid());
                $user->save();
                $activation_key = $user->activationKey;
                /* $this->forgatePasswordEmailpop($user->username, $activation_key); */
                echo CJSON::encode(array(
                    'status' => 'success',
                ));
                Yii::app()->end();
            } else {
                $error = CActiveForm::validate($form);
                if ($error != '[]')
                    echo $error;
                Yii::app()->end();
            }
        }
    }

    public function forgatePasswordEmailpop($username, $activation_key) {
        $mailmodel = EmailTemplate::model()->findByPk(Message::FORGOTPASSWORD_TEMPLATE);
        $mailbody = array('value' => $mailmodel->body, 'type' => 'raw');
        $subject = $mailmodel->subject;
        $mailto = $username;
        $arrayFind = array('[username]', '[activation_link]');
        $arrayReplace = array($mailto, $activation_key);
        $mailbody = str_replace($arrayFind, $arrayReplace, $mailbody);
        $mailtemp = Template::model()->findByPk($mailmodel->template_id);
        $subject = $mailmodel->subject;
        $body = $this->renderPartial('frontend.www.themes.front-end.views.mails/' . $mailtemp->filename, array('mailbody' => $mailbody['value']), true, false);

        try {
            SkillSendMail::SendMail($mailto, $subject, $body);
            /* $this->redirect(array('view', 'id' => $model->id)); */
        } catch (Exception $e) {
            echo $e;
            exit;
        }
        return true;
    }

    public function forgatePasswordEmail($username, $activation_url) {
        $mailmodel = EmailTemplate::model()->findByPk(Message::FORGOTPASSWORD_TEMPLATE);
        $mailbody = array('value' => $mailmodel->body, 'type' => 'raw');
        $subject = $mailmodel->subject;
        $mailto = $username;
        $arrayFind = array('[username]', '[activation_link]');
        $arrayReplace = array($mailto, $activation_url);
        $mailbody = str_replace($arrayFind, $arrayReplace, $mailbody);
        $mailtemp = Template::model()->findByPk($mailmodel->template_id);
        $subject = $mailmodel->subject;
        $body = $this->renderPartial('frontend.www.themes.front-end.views.mails/' . $mailtemp->filename, array('mailbody' => $mailbody['value']), true, false);

        try {
            SkillSendMail::SendMail($mailto, $subject, $body);
            /* $this->redirect(array('view', 'id' => $model->id)); */
        } catch (Exception $e) {
            echo $e;
            exit;
        }
        return true;
    }

    public function actionAssign() {
        Relation::handleAjaxRequest($_POST);
    }

    public function actionMyprofile() {
        // Display my own profile:
        if (!isset($_GET['id']) || $_GET['id'] == Yii::app()->user->id) {
            if (Yii::app()->user->id) {
                $model = $this->loadUser(Yii::app()->user->id);
                $this->render('/user/myprofile', array(
                    'model' => $model,
                    'profile' => $model->profile,
                ));
            }
        } else {
            // Display a foreign profile:

            $model = $this->loadUser($uid = $_GET['id']);

            if ($this->module->forceProtectedProfiles == true ||
                    $model->profile->privacy == 'protected' ||
                    $model->profile->privacy == 'private') {
                $this->render('/user/profilenotallowed');
            } else {
                $this->render('/user/foreignprofile', array(
                    'model' => $model,
                    'profile' => $model->profile,
                ));
            }
        }
    }

    public function actionChangestatus($id) {
        changeStatus('User', 'status', $id);
        $this->redirect(array('/user/user/admin'));
    }

    public function loadUser($uid = 0) {
        if ($this->_model === null) {
            if ($uid != 0)
                $this->_model = User::model()->findByPk($uid);
            elseif (isset($_GET['id']))
                $this->_model = User::model()->findByPk($_GET['id']);
            if ($this->_model === null)
                throw new CHttpException(404, 'The requested User does not exist.');
        }
        return $this->_model;
    }

    public function auto_login($user_email) {
        $user = User::model()->findByAttributes(array('username' => $user_email));
        User::model()->updateByPk($user->id, array('password' => md5($user_email)));
        $identity = new UserIdentity($user_email, $user_email);
        $identity->authenticate();
        Yii::app()->user->login($identity);
        $_SESSION['id'] = Yii::app()->user->id;
        if (Yii::app()->user->id) {
            ShoppingCartByUser::saveCartbyUser(Yii::app()->user->id);
        }
        $this->redirect(Yii::app()->user->returnUrl);
    }

    public function senduserActivationEmail($usermail) {
        $mailmodel = EmailTemplate::model()->findByPk(Message::WELCOME_MSG_REGISTRATION);
        $mailbody = array('value' => $mailmodel->body, 'type' => 'raw');
        $subject = $mailmodel->subject;
        $mailto = $usermail;
        $arrayFind = array('[username]');
        $arrayReplace = array($mailto);
        $mailbody = str_replace($arrayFind, $arrayReplace, $mailbody);
        $mailtemp = Template::model()->findByPk($mailmodel->template_id);
        $subject = $mailmodel->subject;
        $body = $this->renderPartial('frontend.www.themes.front-end.views.mails/' . $mailtemp->filename, array('mailbody' => $mailbody['value']), true, false);
        try {
            SkillSendMail::SendMail($mailto, $subject, $body);
        } catch (Exception $e) {
            echo $e;
            exit;
        }
        return true;
    }

}

